<template>
<teleport to="body" :disabled="!appendToBody">
	<transition name="preview-fade">
		<div
      ref="wrapper"
      :tabindex="-1"
      class="preview"
      :style="{ zIndex }"
			v-if="visible"
    >
			<!-- 蒙层 -->
			<div class="preview__mask" @click.self="hideOnClickModal && hide()"></div>
			<!-- 关闭按钮 -->
			<span v-html="ICON_SVG.close" class="preview__btn preview__close" @click="hide" title="关闭"></span>
			<!-- 左右箭头 -->
			<template v-if="!isSingle">
				<span @click="prev" :class="{ 'is-disabled': !infinite && isFirst }"
					class="preview__btn preview__prev" v-html="ICON_SVG.arrowLeft">
				</span>
				<span @click="next" :class="{ 'is-disabled': !infinite && isLast }"
					class="preview__btn preview__next" v-html="ICON_SVG.arrowRight">
				</span>
			</template>
			<!-- 操作区 -->
			<div class="preview__actions">
        <span v-html="ICON_SVG.zoomOut" class="preview__icon" title="缩小" @click="handleActions('zoomOut')"></span>
        <span v-html="ICON_SVG.zoomIn" class="preview__icon" title="放大" @click="handleActions('zoomIn')"></span>
        <span v-html="ICON_SVG.fullScreen" class="preview__icon" v-show="mode === 'original'" title="原图" @click="toggleMode('fullscreen')"></span>
        <span v-html="ICON_SVG.original" class="preview__icon" v-show="mode === 'fullscreen'" title="1:1" @click="toggleMode('original')"></span>
        <span v-html="ICON_SVG.refreshLeft" class="preview__icon" title="左旋转" @click="handleActions('anticlocelise')"></span>
        <span v-html="ICON_SVG.refreshRight" class="preview__icon" title="右旋转" @click="handleActions('clocelise')"></span>
      </div>
			<!-- 图片展示 -->
			<div class="preview__canvas">
				<img
          v-for="(url, i) in imgPaths"
          v-show="i === index"
          ref="img"
					class="preview__img"
          :key="url"
          :src="url"
          :style="imgStyle"
					@load="handleImgLoad"
          @error="handleImgError"
          @mousedown="handleMouseDown"
        >
				<svg v-if="loading" viewBox="25 25 50 50" class="infinite-scroll__svg">
					<circle cx="50" cy="50" r="20" class="infinite-scroll__circle"></circle>
				</svg>
			</div>
		</div>
	</transition>
</teleport>  
</template>

<script lang='ts'>
import {
  defineComponent, onMounted, computed, PropType, ref, watch, nextTick,
} from 'vue';
import { on, off, rafThrottle, } from './tools';
import {EVENT_CODE, ICON_SVG, INIT_TRANSFORM, ImageViewerAction, mousewheelEventName} from './options';

let prevOverflow = '';
export default defineComponent({
  name: 'Preview',
  props: {
    modelValue: {
      type: Boolean,
      defulat: false,
    },
    // 展示的图片路径列表
    urlList: {
      type: Array as PropType<string[]>,
      default: () => [] as string[],
    },
    // 组件所处层级
    zIndex: {
      type: Number,
      default: 2000,
    },
    // 点击蒙层是否关闭
    hideOnClickModal: {
      type: Boolean,
      default: false,
    },
    // 预览的首张图片的位置
    initialIndex: {
      type: Number,
      default: 0,
    },
    // 是否无限循环预览
    infinite: {
      type: Boolean,
      default: true,
    },
    // 是否将组件插入至 body 元素上
    appendToBody: {
      type: Boolean,
      default: true
    }
  },
  emits: ['close', 'switch', 'update:modelValue'],
  setup(props, { emit }) {
    const visible = ref(false);
    const wrapper = ref(null);
    const img = ref(null);
    const index = ref(props.initialIndex);
    const loading = ref(true);
    // 展示的图片数组
    const imgPaths = ref(props.urlList);
    // 按键按下的处理函数, 但要节流处理一下
    let keyDownHandler: (() => void) | null;
    // 处理鼠标滚动, 但要节流处理一下
    let mouseWheelHandler: (() => void) | null;
    // 拖动事件, 但要节流处理一下
    let dragHandler: () => void;
    // 是否存在箭头
    const isSingle = computed(() => imgPaths.value.length <= 1);
    // 是否是第一张
    const isFirst = computed(() => index.value === 0);
    // 是否是最后一张
    const isLast = computed(() => index.value === imgPaths.value.length - 1);
    // 图片模式, fullscreen: 当前屏幕的宽高比例  original: 原图
    const mode = ref('original');
    // 当前图片路径
    const currentImg = computed(() => imgPaths.value[index.value]);
    // 图片样式
    const transform = ref(INIT_TRANSFORM);
    const imgStyle = computed(() => {
      const {
        scale, deg, offsetX, offsetY, enableTransition,
      } = transform.value;
      const style = {
        transform: `scale(${scale}) rotate(${deg}deg)`,
        transition: enableTransition ? 'transform .3s' : '',
        marginLeft: `${offsetX}px`,
        marginTop: `${offsetY}px`,
      } as CSSStyleDeclaration;
      if (mode.value === 'original') {
        style.maxWidth = '100%';
        style.maxHeight = '100%';
      }
      return style;
    });
    // 显示组件
    function open(imgUrls: string | string[]) {
      if (imgUrls) {
        imgPaths.value = Array.isArray(imgUrls) ? imgUrls : [imgUrls];
      }
      show();
    }
    // 显示组件
    function show() {
      deviceSupportInstall();
      prevOverflow = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      reset();
      visible.value = true;
    }
    // 隐藏组件
    function hide() {
      deviceSupportUninstall();
      document.body.style.overflow = prevOverflow;
      visible.value = false;
      emit('close');
      emit('update:modelValue', false);
    }
    // 组件初始化, 绑定各种事件
    function deviceSupportInstall() {
      keyDownHandler = rafThrottle((e: KeyboardEvent) => {
        switch (e.code) {
          // ESC
          case EVENT_CODE.esc:
            hide();
            break;
          // SPACE
          case EVENT_CODE.space:
            toggleMode(mode.value === 'original' ? 'fullscreen' : 'original');
            break;
          // LEFT_ARROW
          case EVENT_CODE.left:
            prev();
            break;
          // UP_ARROW
          case EVENT_CODE.up:
            handleActions('zoomIn');
            break;
          // RIGHT_ARROW
          case EVENT_CODE.right:
            next();
            break;
          // DOWN_ARROW
          case EVENT_CODE.down:
            handleActions('zoomOut');
            break;
					// no default
        }
      });
      mouseWheelHandler = rafThrottle((e) => {
        const delta = e.wheelDelta ? e.wheelDelta : -e.detail;
        if (delta > 0) {
          handleActions('zoomIn', {
            zoomRate: 0.015,
            enableTransition: false,
          });
        } else {
          handleActions('zoomOut', {
            zoomRate: 0.015,
            enableTransition: false,
          });
        }
      });
      on(document, 'keydown', keyDownHandler);
      on(document, mousewheelEventName, mouseWheelHandler);
    }
    // 组件销毁, 解绑各种事件
    function deviceSupportUninstall() {
      off(document, 'keydown', keyDownHandler!);
      off(document, mousewheelEventName, mouseWheelHandler!);
      keyDownHandler = null;
      mouseWheelHandler = null;
    }
    // 上一张
    function prev() {
      if (isFirst.value && !props.infinite) return;
      const len = imgPaths.value.length;
      index.value = (index.value - 1 + len) % len;
    }
    // 下一张
    function next() {
      if (isLast.value && !props.infinite) return;
      const len = imgPaths.value.length;
      index.value = (index.value + 1) % len;
    }
    // 鼠标在图片上按下事件
    function handleMouseDown(e: MouseEvent) {
      if (loading.value || e.button !== 0) return;

      const { offsetX, offsetY } = transform.value;
      const startX = e.pageX;
      const startY = e.pageY;
      dragHandler = rafThrottle((ev) => {
        transform.value = {
          ...transform.value,
          offsetX: offsetX + ev.pageX - startX,
          offsetY: offsetY + ev.pageY - startY,
        };
      });
      on(document, 'mousemove', dragHandler);
      on(document, 'mouseup', () => {
        off(document, 'mousemove', dragHandler);
      });

      e.preventDefault();
    }
    // 原图与1:1切换
    function toggleMode(type: string) {
      if (loading.value) return;
      mode.value = type;
      reset();
    }
    // 放大/缩小/左旋转/右旋转
    function handleActions(action: ImageViewerAction, options = {}) {
      if (loading.value) return;
      const { zoomRate, rotateDeg, enableTransition } = {
        zoomRate: 0.2,
        rotateDeg: 90,
        enableTransition: true,
        ...options,
      };
      switch (action) {
        case 'zoomOut':
          if (transform.value.scale > 0.2) {
            transform.value.scale = parseFloat((transform.value.scale - zoomRate).toFixed(3));
          }
          break;
        case 'zoomIn':
          transform.value.scale = parseFloat((transform.value.scale + zoomRate).toFixed(3));
          break;
        case 'clocelise':
          transform.value.deg += rotateDeg;
          break;
        case 'anticlocelise':
          transform.value.deg -= rotateDeg;
          break;
				// no default
      }
      transform.value.enableTransition = enableTransition;
    }
    // 图片加载完毕
    function handleImgLoad() {
      loading.value && (loading.value = false);
    }
    // 图片加载失败
    function handleImgError() {
      loading.value && (loading.value = false);
    }
    // 重置样式
    function reset() {
      transform.value = INIT_TRANSFORM;
    }
    onMounted(() => {
      if (props.modelValue) {
        show();
      }
      // deviceSupportInstall();
      // add tabindex then wrapper can be focusable via Javascript
      // focus wrapper so arrow key can't cause inner scroll behavior underneath
      // wrapper.value?.focus?.();
    });
    // 监听除第一张图片外, 每张图片是否加载完毕了
    watch(currentImg, () => {
      nextTick(() => {
        const $img:HTMLImageElement = img.value!;
        if (!$img.complete) {
          loading.value = true;
        }
      });
    });
    // 监听每次切换
    watch(index, (val) => {
      reset();
      emit('switch', val);
    });
    // 监听v-model
    watch(() => props.modelValue, (val) => {
      if (val) {
        show();
      } else if (visible.value) {
        hide();
      }
    });

    return {
      wrapper,
      img,
      visible,
      imgPaths,
      index,
      isSingle,
      isFirst,
      isLast,
      imgStyle,
      mode,
      loading,
      ICON_SVG,
      hide,
      open,
      prev,
      next,
      handleImgLoad,
      handleImgError,
      handleMouseDown,
      toggleMode,
      handleActions,
    };
  },
});
</script>

<style scoped>
.preview {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
}
.preview__mask {
	position: absolute;
	width: 100%;
	height: 100%;
	top: 0;
	left: 0;
	opacity: .5;
	background: #000;
}
.preview__btn {
	width: 44px;
  height: 44px;
	position: absolute;
	z-index: 10;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 50%;
	opacity: .8;
	cursor: pointer;
	box-sizing: border-box;
	user-select: none;
	background-color: rgb(96 98 102);
}
.preview__close {
	top: 40px;
	right: 40px;
}
.preview__prev {
	top: 50%;
  transform: translateY(-50%);
	left: 40px;
}
.preview__next {
	top: 50%;
  transform: translateY(-50%);
	right: 40px;
}
.preview__img {
	cursor: move;
	z-index: 1;
}
.is-disabled {
  cursor: no-drop !important;
}
.preview__actions {
	background-color: rgb(96 98 102);
	position: absolute;
  z-index: 10;
	left: 50%;
	bottom: 30px;
	transform: translateX(-50%);
	display: flex;
	align-items: center;
	justify-content: center;
	opacity: .8;
	cursor: pointer;
	box-sizing: border-box;
	user-select: none;
	border-radius: 22px;
	width: 282px;
  height: 44px;
	padding: 0 23px;
}
.preview__icon {
	width: 24px;
	height: 24px;
	margin: 0 12px;
}
.preview__canvas {
	width: 100%;
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center
}
@keyframes preview-fade-in {
  0% {
    -webkit-transform: translate3d(0, -20px, 0);
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
  100% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
}
@keyframes preview-fade-out {
  0% {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
    opacity: 1;
  }
  100% {
    -webkit-transform: translate3d(0, -20px, 0);
    transform: translate3d(0, -20px, 0);
    opacity: 0;
  }
}
.infinite-scroll__svg{
  transform-origin: center;
  animation: rotate 2s linear infinite;
	width: 50px;
	position: absolute;
	z-index: 0;
}
.infinite-scroll__circle{
  fill: none;
  stroke-width: 3;
  stroke-dasharray: 1, 200;
  stroke-dashoffset: 0;
  stroke-linecap: round;
  animation: dash 1.5s ease-in-out infinite;
	stroke: #a5a5a5;
}
@keyframes rotate {
  100% {
    transform: rotate(360deg);
  }
}
@keyframes dash {
  0% {
    stroke-dasharray: 1, 200;
    stroke-dashoffset: 0;
  }
  50% {
    stroke-dasharray: 90, 200;
    stroke-dashoffset: -35px;
  }
  100% {
    stroke-dashoffset: -125px;
  }
}
</style>
